package com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.api;

import cn.hutool.json.JSONUtil;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.dto.PPTThemeListRequest;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.dto.PPTThemeListResponse;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.util.ApiAuthAlgorithm;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * PPT主题列表查询API
 * 调用讯飞开放平台查询PPT模板主题列表
 */
@Slf4j
@Component
public class PPTThemeListQuery {

    @Value("${xunfei.api.ppt.theme-list-url}")
    private String themeListUrl;

    @Value("${xunfei.api.ppt.app-id}")
    private String appId;

    @Value("${xunfei.api.ppt.api-key}")
    private String apiKey;

    private static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8";
    private final static OkHttpClient client = new OkHttpClient().newBuilder()
            .connectionPool(new ConnectionPool(100, 5, TimeUnit.MINUTES))
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    /**
     * 查询PPT主题列表
     *
     * @param request 请求参数
     * @return 主题列表响应
     */
    public PPTThemeListResponse queryPPTThemeList(PPTThemeListRequest request) {
        try {
            log.info("开始查询PPT主题列表，参数: {}", JSONUtil.toJsonStr(request));
            
            // 准备请求体
            String requestBody = JSONUtil.toJsonStr(request);
            RequestBody body = RequestBody.create(requestBody, MediaType.get(MEDIA_TYPE_JSON));
            
            // 获取时间戳和签名
            long timestamp = System.currentTimeMillis()/1000;
            String ts = String.valueOf(timestamp);

            ApiAuthAlgorithm auth = new ApiAuthAlgorithm();
            String signature = auth.getSignature(appId, apiKey, timestamp);
            
            // 构建请求
            Request httpRequest = new Request.Builder()
                    .url(themeListUrl)
                    .addHeader("Content-Type", MEDIA_TYPE_JSON)
                    .addHeader("appId", appId)
                    .addHeader("timestamp", ts)
                    .addHeader("signature", signature)
                    .post(body)
                    .build();
            
            // 发送请求
            try (Response response = client.newCall(httpRequest).execute()) {
                String responseBody = response.body().string();
                log.info("PPT主题列表查询结果: {}", responseBody);
                
                // 解析响应
                if (response.isSuccessful()) {
                    return JSONUtil.toBean(responseBody, PPTThemeListResponse.class);
                } else {
                    log.error("PPT主题列表查询失败，状态码: {}, 响应: {}", response.code(), responseBody);
                    return buildErrorResponse("请求失败: " + response.code());
                }
            }
        } catch (IOException e) {
            log.error("PPT主题列表查询异常", e);
            return buildErrorResponse("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 构建错误响应
     */
    private PPTThemeListResponse buildErrorResponse(String message) {
        PPTThemeListResponse errorResponse = new PPTThemeListResponse();
        errorResponse.setFlag(false);
        errorResponse.setCode(-1);
        errorResponse.setDesc(message);
        return errorResponse;
    }
} 